package com.example.lancooznbk.view.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.lancooznbk.R;
import com.example.lancooznbk.model.result.RecentStudyItemEntity;
import com.example.lancooznbk.view.widget.DecoratorViewPager;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import znbkFragment.ZnbkMainFragment;
import znbkListBj.activity.NotesListActivity;
import znbkListCtfd.activity.WrongTopicTutoringListActivity;
import znbkListNtxl.activity.TrainingDifficultProblemsListActivity;
import znbkListRdqh.activity.WeekAscensionListActivity;
import znbkListRdtz.activity.HeatPointExtensionListActivity;
import znbkListSc.activity.CollectionListActivity;
import znbkListXtfx.activity.SystemReviewListActivity;

/**
 * Created by Administrator on 2018\1\26 0026.
 * 主界面所有下布局的加载
 */


public class HeaderBottomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    //item类型
    public static final int ITEM_TYPE_VIEWPAGER = 0;
    public static final int ITEM_TYPE_HEADER = 1;
    public static final int ITEM_TYPE_CONTENT = 2;
    public static final int ITEM_TYPE_BOTTOM = 3;
    //模拟数据
//    public String [] texts={"java","python","C++","Php",".NET"};
    public List<RecentStudyItemEntity.LastAnswerBean> LastAnswerDate;
    private LayoutInflater mLayoutInflater;
    private static Context mContext;
    private int mViewpagerCount = 1;//头部View个数
    private int mHeaderCount = 1;//头部View个数
    private int mBottomCount = 1;//底部View个数
    public DecoratorViewPager viewPager;
    public ArrayList<View> views = new ArrayList<>();
    public ArrayList<ImageView> pointImageView = new ArrayList<>();
    public View viewPagerscoring_background;
    public View viewPagerlearning_process;
    public View viewPagerability_to_change;
    public TextView folding_TV;
    /**
     * 定义script的正则表达式
     */
    private static final String REGEX_SCRIPT = "<script[^>]*?>[\\s\\S]*?<\\/script>";
    /**
     * 定义style的正则表达式
     */
    private static final String REGEX_STYLE = "<style[^>]*?>[\\s\\S]*?<\\/style>";
    /**
     * 定义HTML标签的正则表达式
     */
    private static final String REGEX_HTML = "<[^>]+>";
    /**
     * 定义空格回车换行符
     */
    private static final String REGEX_SPACE = "\\s*|\t|\r|\n";

    public HeaderBottomAdapter(Context context, List<RecentStudyItemEntity.LastAnswerBean> LastAnswerDate, ArrayList<View> views,TextView folding_TV) {
        mContext = context;
        Log.e("HeaderBottomAdapter", "HeaderBottomAdapter");
        this.LastAnswerDate = LastAnswerDate;
        this.views = views;
        this.folding_TV = folding_TV;
        mLayoutInflater = LayoutInflater.from(context);
    }

    //内容长度
    public int getContentItemCount() {
        if (LastAnswerDate != null) {
            return LastAnswerDate.size();
        } else {
            return 0;
        }
    }

    /*  //判断当前item是否是HeadView
      public boolean isHeaderViewpager(int position) {
          return mViewpagerCount != 0 && position < mViewpagerCount;
      }*/
    //判断当前item是否是HeadView
    public boolean isViewPagerView(int position) {
        return mViewpagerCount != 0 && position < mViewpagerCount;
    }

    //判断当前item是否是HeadView
    public boolean isHeaderView(int position) {
        return mHeaderCount != 0 && position < mHeaderCount + mViewpagerCount;
    }

    //判断当前item是否是FooterView
    public boolean isBottomView(int position) {
        return mBottomCount != 0 && position >= (mHeaderCount + getContentItemCount() + mViewpagerCount);
    }

    //判断当前item类型
    @Override
    public int getItemViewType(int position) {
        int dataItemCount = getContentItemCount();
        if (mViewpagerCount != 0 && position < mViewpagerCount) {
            return ITEM_TYPE_VIEWPAGER;
        } else if (mHeaderCount != 0 && position < mHeaderCount + mViewpagerCount) {
            //头部View
            return ITEM_TYPE_HEADER;
        } else if (mBottomCount != 0 && position >= (mHeaderCount + dataItemCount + mViewpagerCount)) {
            //底部View
            return ITEM_TYPE_BOTTOM;
        } else {
            //内容View
            return ITEM_TYPE_CONTENT;
        }
    }

    //内容 ViewHolder
    public static class ContentViewHolder extends RecyclerView.ViewHolder {
        public ImageView iv_picture;
        public TextView tv_paperSummary22;
        public TextView fromid;
        public TextView tv_time;

        public ContentViewHolder(View itemView) {
            super(itemView);
            iv_picture = (ImageView) itemView.findViewById(R.id.iv_picture);
            tv_paperSummary22 = (TextView) itemView.findViewById(R.id.tv_paperSummary22);
            fromid = (TextView) itemView.findViewById(R.id.fromid);
            tv_time = (TextView) itemView.findViewById(R.id.tv_time);
        }
    }

    //头部 ViewHolder
    public static class HeaderViewpagerHolder extends RecyclerView.ViewHolder {
        public View itemViews;

        public HeaderViewpagerHolder(View itemView) {
            super(itemView);
            itemViews = itemView;

        }
    }

    public class MyAdapter extends PagerAdapter {

        public MyAdapter() {
        }

        @Override
        public int getCount() {
            Log.e("getCount", "return 3");
            return 3;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            Log.e("isViewFromObject", "arg0 == arg1");
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            Log.e("destroyItem", "((ViewPager)container).removeView(views.get(position))");
            container.removeView(views.get(position));
        }

        /**
         * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Log.e("aaaainstantiateItem", "aaasssa" + position);
            Log.e("aaaainstantiateItem", "views.size()" + views.size());
            container.addView(views.get(position));
            return views.get(position);
        }
    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        public void onPageScrollStateChanged(int arg0) {
            Log.e("aaaa", "onPageScrollStateChanged");
            //该方法是ViewPager滑动结束后，页面别选定后调用此方法
            /*在ViewPager滑动结束后需要通知父容器（ListView）可以
             * 对后续的事件进行适当的处理了（包括自身事件的拦截）*/
            //     mXRefreshView.requestDisallowInterceptTouchEvent(false);
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {
            Log.e("aaaa", "onPageScrolled");
            Log.e("arg0", "arg0+" + arg0 + "   " + views.size());
            //该方法是ViewPager滑动时调用此方法
            /*在ViewPager滑动时需要通知父容器（ListView）不要拦截,
            也就是说此事件交给ViewPager处理*/
            //     mXRefreshView.requestDisallowInterceptTouchEvent(true);
        }

        public void onPageSelected(int arg0) {
            Log.e("arg0", "arg0+" + arg0 + "   " + views.size());
            if(arg0 == 0){
                String  predictionscoreTX = (String) ((TextView)views.get(arg0).findViewById(R.id.PredictionscoreTV)).getText();;
                Log.e("onPageSelected", "predictionscoreTX " + predictionscoreTX);
                if (predictionscoreTX != "" ){

                    folding_TV.setText("预测得分:"+ predictionscoreTX);
                }
            }else if(arg0 == 1){
                String  learning_processTVTX = (String) ((TextView)views.get(arg0).findViewById(R.id.learning_processTV)).getText();;
                Log.e("onPageSelected", "learning_processTVTX " + learning_processTVTX);
                if (learning_processTVTX != "" ){
                    folding_TV.setText("学习进度:"+learning_processTVTX);
                }
            }else if(arg0 == 2){
                String  data_TextViewTX = (String) ((TextView)views.get(arg0).findViewById(R.id.data_TextView)).getText();;
                Log.e("onPageSelected", "data_TextViewTX " + data_TextViewTX);
                if (data_TextViewTX != "" ){
//                    folding_TV.setText("本月能力值:"+data_TextViewTX);
                    folding_TV.setText("本周能力值:"+data_TextViewTX);
                }
            }
            setImageBackground(arg0);
        }
    }

    /**
     * 设置选中的tip的背景
     *
     * @param
     */
    public void setImageBackground(int selectItems) {
        Log.e("selectItems", "selectItems+" + selectItems);
        for (int i = 0; i < 3; i++) {
            Log.e("selectItems", "selectItems+" + pointImageView.get(i));
            if (i == selectItems) {
                pointImageView.get(i).setAlpha(255);
//                    pointImageView.get(i).setImageResource(R.drawable.dot_button);
            } else {
                pointImageView.get(i).setAlpha(100);
//                    pointImageView.get(i).setImageResource(R.drawable.dot_buttons);
            }
        }
    }

    //头部 ViewHolder
    public static class HeaderViewHolder extends RecyclerView.ViewHolder {
        public HeaderViewHolder(View itemView) {
            super(itemView);
            /*
           * 主界面学习模块按钮
           * 系统复习
           * */
            LinearLayout mLayoutSystemReview;
            mLayoutSystemReview = (LinearLayout) itemView.findViewById(R.id.layout_system_review);
            mLayoutSystemReview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e("setOnClickListener", "setOnClickListener");
                    Intent intent = new Intent(mContext, SystemReviewListActivity.class);
                    mContext.startActivity(intent);
                }
            });

            /*
           * 主界面学习模块按钮
           * 弱点强化
           * */
            LinearLayout mLayoutWeekAscension;
            mLayoutWeekAscension = (LinearLayout) itemView.findViewById(R.id.layout_week_ascension);
            mLayoutWeekAscension.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, WeekAscensionListActivity.class);
                    mContext.startActivity(intent);
                }
            });

             /*
           * 主界面学习模块按钮
           * 难题训练
           * */
            LinearLayout mLayoutTrainingDifficultProblems;
            mLayoutTrainingDifficultProblems = (LinearLayout) itemView.findViewById(R.id.layout_training_difficult_problems);
            mLayoutTrainingDifficultProblems.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, TrainingDifficultProblemsListActivity.class);
                    mContext.startActivity(intent);
                }
            });

            /*
           * 主界面学习模块按钮
           * 错题辅导
           * */
            LinearLayout mLayoutHeatPointExtension;
            mLayoutHeatPointExtension = (LinearLayout) itemView.findViewById(R.id.layout_heat_point_extension);
            mLayoutHeatPointExtension.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, HeatPointExtensionListActivity.class);
                    mContext.startActivity(intent);
                }
            });

            /*
           * 主界面学习模块按钮
           * 错题辅导
           * */
            LinearLayout mLayoutWrongTopicTutoring;
            mLayoutWrongTopicTutoring = (LinearLayout) itemView.findViewById(R.id.layout_wrong_topic_tutoring);
            mLayoutWrongTopicTutoring.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, WrongTopicTutoringListActivity.class);
                    mContext.startActivity(intent);
                }
            });

        }
    }

    //底部 ViewHolder
    public static class BottomViewHolder extends RecyclerView.ViewHolder {
        public BottomViewHolder(View itemView) {
            super(itemView);


              /*
           * 主界面学习模块按钮
           * 笔记列表
           * */
            LinearLayout mLayoutNotes;
            mLayoutNotes = (LinearLayout) itemView.findViewById(R.id.layout_notes);
            mLayoutNotes.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, NotesListActivity.class);
                    mContext.startActivity(intent);
                }
            });

            /*
           * 主界面学习模块按钮
           * 收藏列表
           * */
            LinearLayout mLayoutCollection;
            mLayoutCollection = (LinearLayout) itemView.findViewById(R.id.layout_collection);
            mLayoutCollection.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, CollectionListActivity.class);
                    mContext.startActivity(intent);
                }
            });

        }

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE_VIEWPAGER) {
            return new HeaderViewpagerHolder(mLayoutInflater.inflate(R.layout.layout_main_interface_menu, parent, false));
        } else if (viewType == ITEM_TYPE_HEADER) {
            return new HeaderViewHolder(mLayoutInflater.inflate(R.layout.rv_header, parent, false));
        } else if (viewType == ITEM_TYPE_CONTENT) {
            return new ContentViewHolder(mLayoutInflater.inflate(R.layout.item_rv_zjxx, parent, false));
        } else if (viewType == ITEM_TYPE_BOTTOM) {
            return new BottomViewHolder(mLayoutInflater.inflate(R.layout.rv_footer, parent, false));
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof HeaderViewpagerHolder) {
            //载入图片资源ID
            viewPager = (DecoratorViewPager) ((HeaderViewpagerHolder) holder).itemViews.findViewById(R.id.viewPager);
            ImageView ImageView3 = (ImageView) ((HeaderViewpagerHolder) holder).itemViews.findViewById(R.id.ImageView3);
            ImageView ImageView2 = (ImageView) ((HeaderViewpagerHolder) holder).itemViews.findViewById(R.id.ImageView2);
            ImageView ImageView1 = (ImageView) ((HeaderViewpagerHolder) holder).itemViews.findViewById(R.id.ImageView1);
            Log.e("ImageView1", "ImageView12+" + ImageView1);
            Log.e("ImageView2", "ImageView22+" + ImageView2);
            Log.e("ImageView3", "ImageView32+" + ImageView3);
            pointImageView.add(ImageView1);
            pointImageView.add(ImageView2);
            pointImageView.add(ImageView3);


            MyAdapter pagerAdapter = new MyAdapter();
//            viewPager.setNestedpParent(mXRefreshView);
            //绑定适配器
            viewPager.setAdapter(pagerAdapter);
            //设置viewPager的初始界面为第一个界面
            viewPager.setCurrentItem(0);
            Log.e("onBindViewHolder", "viewPager getChildCount+" + viewPager.getChildCount());
            setImageBackground(0);
            viewPager.addOnPageChangeListener(new MyOnPageChangeListener());
        } else if (holder instanceof HeaderViewHolder) {
        } else if (holder instanceof ContentViewHolder) {
//            ((ContentViewHolder) holder).textView.setText(texts[position - mHeaderCount]);
            Log.e("onBindViewHolder","ContentViewHolder");
            Log.e("LastAnswerDate ","LastAnswerDate+"+LastAnswerDate);
            if (LastAnswerDate != null) {
                Log.e("LastAnswerDate","position+"+position);
                if (LastAnswerDate.get(position - 2).getResType().equals("1")) {
                    ((ContentViewHolder) holder).iv_picture.setImageResource(R.mipmap.znbk_recent_study_type_of_txt);
                } else if (LastAnswerDate.get(position - 2).getResType().equals("2")) {
                    ((ContentViewHolder) holder).iv_picture.setImageResource(R.mipmap.znbk_recent_study_type_of_pictude);
                } else if (LastAnswerDate.get(position - 2).getResType().equals("3") || LastAnswerDate.get(position - 2).getResType().equals("5")) {
                    ((ContentViewHolder) holder).iv_picture.setImageResource(R.mipmap.znbk_recent_study_type_of_audio);
                } else if (LastAnswerDate.get(position - 2).getResType().equals("4") || LastAnswerDate.get(position - 2).getResType().equals("6")) {
                    ((ContentViewHolder) holder).iv_picture.setImageResource(R.mipmap.znbk_recent_study_type_of_video);
                } else if (LastAnswerDate.get(position - 2).getResType().equals("P")) {
                    ((ContentViewHolder) holder).iv_picture.setImageResource(R.mipmap.znbk_recent_study_type_of_test);
                } else {
                    ((ContentViewHolder) holder).iv_picture.setImageResource(R.mipmap.znbk_recent_study_type_of_question);
                }
                Log.e("Html.fromHtml","Html.fromHtml"+Html.fromHtml(LastAnswerDate.get(position - 2).getTitle().replaceAll("&nbsp;", "")).toString().trim());

                ((ContentViewHolder) holder).tv_paperSummary22.setText((Html.fromHtml(LastAnswerDate.get(position - 2).getTitle().replaceAll("&nbsp;", "")).toString().trim()));
                if (LastAnswerDate.get(position - 2).getModuleType() == 1) {
                    ((ContentViewHolder) holder).fromid.setText("系统复习");
                } else if (LastAnswerDate.get(position - 2).getModuleType() == 2) {
                    ((ContentViewHolder) holder).fromid.setText("弱点强化");
                } else if (LastAnswerDate.get(position - 2).getModuleType() == 3) {
                    ((ContentViewHolder) holder).fromid.setText("热点拓展");
                } else if (LastAnswerDate.get(position - 2).getModuleType() == 4) {
                    ((ContentViewHolder) holder).fromid.setText("难点训练");
                } else if (LastAnswerDate.get(position - 2).getModuleType() == 5) {
                    ((ContentViewHolder) holder).fromid.setText("错题辅导");
                }
                ((ContentViewHolder) holder).tv_time.setText( LastAnswerDate.get(position - 2).getUpdateTime().replaceAll("-", ".").split(" ")[0]);
            }


        } else if (holder instanceof BottomViewHolder) {
        }
    }

    @Override
    public int getItemCount() {
        return mHeaderCount + getContentItemCount() + mBottomCount + mViewpagerCount;
    }

    public void addData(int position,List<RecentStudyItemEntity.LastAnswerBean> LastAnswerDate) {
//      在list中添加数据，并通知条目加入一条
//        list.add(position, "我是商品" + position);
        //添加动画
        this.LastAnswerDate = LastAnswerDate;
        getContentItemCount();
        Log.e("addData","addData");
        notifyItemInserted(position);
    }
    //  删除数据
    public void removeData(int position) {
//        list.remove(position);
        //删除动画
//        views.remove(2);
        notifyItemRemoved(position);
        notifyItemRangeChanged(position,4 - position);
        notifyDataSetChanged();
    }

    public static String delHTMLTag(String htmlStr) {
        // 过滤script标签
        Pattern p_script = Pattern.compile(REGEX_SCRIPT, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll("");
        // 过滤style标签
        Pattern p_style = Pattern.compile(REGEX_STYLE, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll("");
        // 过滤html标签
        Pattern p_html = Pattern.compile(REGEX_HTML, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll("");
        // 过滤空格回车标签
        Pattern p_space = Pattern.compile(REGEX_SPACE, Pattern.CASE_INSENSITIVE);
        Matcher m_space = p_space.matcher(htmlStr);
        htmlStr = m_space.replaceAll("");
        return htmlStr.trim(); // 返回文本字符串
    }
}